package com.yang.qgg_demo.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.qgg_demo.common.R;
import com.yang.qgg_demo.controller.dto.UserDTO;
import com.yang.qgg_demo.entity.Goods;
import com.yang.qgg_demo.mapper.UserMapper;
import com.yang.qgg_demo.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import com.yang.qgg_demo.service.IUserService;
import com.yang.qgg_demo.entity.User;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.View;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yang
 * @since 2024-09-23
 */
@RestController
@Slf4j
@RequestMapping("/user")
    public class UserController {

    @Resource
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;


    @GetMapping("/login")
    public R login(Integer userid, String password) throws UnsupportedEncodingException {
        User user = userService.getById(userid);
        if (user == null || !user.getPassword().equals(password)) {
            return R.error("用户名或密码错误");
        }

        UserDTO userDTO = new UserDTO();

        userDTO.setId(userid);
        userDTO.setAvatarUrl(user.getAvatar());
        userDTO.setPassword(password);
        userDTO.setNickname(user.getNickname());

        String token1 = TokenUtils.genToken1(userid,userDTO.getPassword());
//        String token2 = TokenUtils.genToken2(userDTO,userDTO.getPassword());
        userDTO.setToken(token1);

        if (user!=null&&password.equals(user.getPassword())){
            return R.success(userDTO);
        }
        return R.error("用户名或密码错误");
    }

    @PostMapping("/save")
    public R save(@RequestBody User user) {
        if (userService.getById(user.getUserid())!=null){
            return R.error("ID已经存在");
        }
        try {
            // 初始化为普通用户，假设普通用户的 roleid 为 2
            user.setRoleid(2);
            // 插入用户信息
            int result = userMapper.insert(user);

            // 判断插入是否成功
            if (result > 0) {
                return R.success("成功建立");
            } else {
                return R.error("新建错误");
            }
        } catch (Exception e) {
            // 处理异常情况
            e.printStackTrace();
            return R.error("系统错误: " + e.getMessage());
        }
    }

    @PostMapping("/insert")
    public R insert(@RequestBody User user) {
        if (userService.getById(user.getUserid())!=null){
            userService.updateById(user);
        }
        return R.success("修改信息成功");
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        log.info(String.valueOf(id));
        if (userService.removeById(id)){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    @GetMapping
    public List<User> findAll() {
        return userService.list();
    }

    @GetMapping("/{id}")
    public User findOne(@PathVariable Integer id) {
        return userService.getById(id);
    }

//    @GetMapping("/page")
//    public Page<User> findPage(@RequestParam Integer pageNum,
//                                    @RequestParam Integer pageSize) {
//
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
////        queryWrapper.orderByDesc(true,"id");
//
//        return userService.page(new Page<>(pageNum, pageSize),queryWrapper);
//    }

    @GetMapping("/page")
    public Page<User> findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,String nickname,String email) {


        LambdaQueryWrapper<User> queryWrapper = new  LambdaQueryWrapper<>();
        Page pageInfo=new Page(pageNum, pageSize);
        queryWrapper.like(StringUtils.isNotEmpty(nickname),User::getNickname,nickname);
        queryWrapper.like(StringUtils.isNotEmpty(email),User::getEmail,email);

        return userService.page(pageInfo,queryWrapper);
    }


    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库查出所有数据
        List<User> list = userService.list();
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("avatar", "头像");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("create_time", "创建时间");

        writer.write(list, true);

        //设置游览器的响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");

        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        // 关闭writer，释放内存
        writer.close();

    }

    @PostMapping("/import")
    public void imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader excelReader = ExcelUtil.getReader(inputStream);
        List<User> list = excelReader.readAll(User.class);
        userService.saveBatch(list);
    }

    @GetMapping("/getuser")
    public User getUser(){
        //获取到当前登录的id号
        String currentUser =  TokenUtils.getUser();
        int id = Integer.parseInt(currentUser);
        if (id>0){
            return userService.getById(id);
        }
        return null;
    }

}

